package com.jinsilu.freight.other;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.HandlerThread;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.blankj.utilcode.util.LogUtils;
import com.hdgq.locationlib.LocationOpenApi;
import com.hdgq.locationlib.entity.ShippingNoteInfo;
import com.hdgq.locationlib.listener.OnSendResultListener;
import com.jinsilu.freight.R;
import com.jinsilu.freight.helper.CommonHelper;

import java.util.List;

/**
 * @author byd
 * @time 2021/11/29 17:09
 */
public class ForegroundService extends Service {

    private static final int SERVICE_ID = 1;

    private CountDownTimer countDownTimer;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("ForegroundService", "ForegroundService:  前台服务创建了");

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { // 4.3-7.0
            startForeground(SERVICE_ID, new Notification());
            startService(new Intent(this, InnerService.class));
        } else { // 8.0及以上
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel("channel", "网络货运定位服务", NotificationManager.IMPORTANCE_HIGH);
            //呼吸灯关闭
            channel.enableLights(false);
            //震动关闭
            channel.enableVibration(false);
            //角标关闭
            channel.setShowBadge(false);
            manager.createNotificationChannel(channel);
            Notification notification = new NotificationCompat.Builder(this, "channel")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("网络货运定位服务")
                    .setContentText("网络货运监管平台要求，需要在运输过程中的特定时间上传定位信息，请勿强制清理应用！")
                    .build();
            startForeground(SERVICE_ID, notification);
        }

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (null == intent || null == intent.getSerializableExtra("ShippingNoteInfo")) {
            return START_NOT_STICKY;
        }
        ShippingNoteInfo shippingNoteInfo = (ShippingNoteInfo) intent.getSerializableExtra("ShippingNoteInfo");
        new HandlerThread("WorkThread") {
            @Override
            protected void onLooperPrepared() {
                cuntDown(shippingNoteInfo);
            }
        }.start();
        return START_REDELIVER_INTENT;
    }

    /**
     * 网络货运SDK Send调用
     *
     * @param tempShipNoteInfo 信息列表
     */
    private void cuntDown(ShippingNoteInfo tempShipNoteInfo) {
        /*缓存SDK所需信息*/
        CommonHelper.saveObject("sdk", tempShipNoteInfo);
        long interval = tempShipNoteInfo.getInterval();
        LogUtils.e("间隔时间：", interval);
        /*
         * CountDownTimer 实现倒计时 上传信息
         */
        if (null != countDownTimer) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        countDownTimer = new CountDownTimer(interval, MTLConstants.ONCE_TIME) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                LogUtils.e("中间点上传：");
                ShippingNoteInfo shippingNoteInfo = new ShippingNoteInfo();
                shippingNoteInfo.setShippingNoteNumber(tempShipNoteInfo.getShippingNoteNumber());
                shippingNoteInfo.setSerialNumber(tempShipNoteInfo.getSerialNumber());
                ShippingNoteInfo[] shippingNoteNumbers = new ShippingNoteInfo[]{shippingNoteInfo};
                /*
                 * context 上下文
                 * vehicleNumber 车牌号
                 * driverName 司机姓名
                 * remark 备注
                 * shippingNoteNumbers 运单信息列表
                 * listener 结果回调函数
                 */
                LocationOpenApi.send(getApplicationContext(), tempShipNoteInfo.getVehicleNumber(), tempShipNoteInfo.getDriverName(), "", shippingNoteNumbers, new OnSendResultListener() {
                    @Override
                    public void onFailure(String errorCode, String errorMsg, List<ShippingNoteInfo> list) {
                        LogUtils.e(String.format("监管平台SDK发送错误：ErrorCode%s ErrorMsg%s", errorCode, errorMsg));
                    }

                    @Override
                    public void onSuccess(List<ShippingNoteInfo> list) {
                        if (list.isEmpty()) return;
                        cuntDown(list.get(0));
                    }
                });
            }
        };
        //调用 CountDownTimer 对象的 start() 方法开始倒计时，也不涉及到线程处理
        countDownTimer.start();
    }

    @Override
    public void onDestroy() {
        if (null != countDownTimer) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        // 移除前台任务
        stopForeground(true);
        // 任务完成，终止自己
        stopSelf();
        super.onDestroy();
    }

    public static class InnerService extends Service {

        @Override
        public void onCreate() {
            super.onCreate();
            Log.i("ForegroundService", "ForegroundService: InnerService服务创建了");

            startForeground(SERVICE_ID, new Notification());
            stopSelf();
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {

            return null;
        }
    }
}
